//
//  PublicationTopicViewController.m
//  安好
//
//  Created by rlp on 14-12-3.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "PublicationTopicViewController.h"

@interface PublicationTopicViewController ()
{
    //存取图片的url
    NSMutableArray *imageURlArrays;
    NSMutableArray *halfImageURL;
    
    NSMutableArray *arrimages;//查看的图片
    NSInteger indeximage;//点击的第几个image
//    MJPhotoBrowser *browser;
    
    
    
    
    
    
    
}
@end

@implementation PublicationTopicViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (!self.imageArr) {
        self.imageArr = [[NSMutableArray alloc]initWithCapacity:10];
    }
    [self.imageArr addObject:[UIImage imageNamed:@"咨询_添加照片"]];
    
    self.imageListView.delegate = self;
    
    // Do any additional setup after loading the view from its nib.
    self.edgesForExtendedLayout=UIRectEdgeNone;
    self.view.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    
    self.subject.delegate = self;
//    [self.subject becomeFirstResponder];
    self.imageListView.hidden = YES;
    self.cameraBtn.hidden = !self.imageListView.hidden;
//    [self registerForKeyboardNotifications];
    imageURlArrays = [[NSMutableArray alloc]initWithCapacity:10];
    halfImageURL= [[NSMutableArray alloc]initWithCapacity:10];
    
    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    tapGr.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGr];
    [self makeNavBarView];

    
}
-(IBAction)viewTapped:(id)sender{
    [self.view endEditing:NO];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - 设置导航条
-(void)makeNavBarView
{
    self.navigationItem.rightBarButtonItem = nil;
    self.navigationItem.title = [NSString stringWithFormat:@"%@",@"发布话题"];
    //贴图
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonClicked:)];
    backBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnImg;
    UIButton *rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 23, 23)];
    [rightButton setImage:[UIImage imageNamed:@"公用_完成"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(rightButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
    
}
#pragma mark -
#pragma mark -- click
-(void)leftButtonClicked:(UIButton *)sender
{
    [self hiddenLabel];
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)rightButtonClicked:(UIButton *)sender
{
    [self.subject resignFirstResponder];
    [self.contentTextView resignFirstResponder];

//    platform	平台 ios/android
//    version	版本号
//    thread	MCRYPT_3DES（加密方式）,包含下面参数
//    gid	圈子id
//    subject	标题
//    message	内容
//    pic	图片
    NSMutableString *multString=[[NSMutableString alloc]init];
    if (halfImageURL.count>0) {
        for (int i=0; i<halfImageURL.count; i++) {
            if (i==0) {
                [multString appendString:[halfImageURL objectAtIndex:i]];
            }else
            {
                [multString appendString:[NSString stringWithFormat:@",%@",[halfImageURL objectAtIndex:i]]];
            }
        }
    }
    else
    {
        NSString *str=@"";
        multString=[NSMutableString stringWithString:str];
    }
    
    
    if (self.subject.text.length==0) {
        alertContent(@"请输入话题的标题");
        [self.subject becomeFirstResponder];
        return;
    }
    if (self.contentTextView.text.length==0) {
        alertContent(@"请输入话题内容");
        [self.contentTextView becomeFirstResponder];
        return;
    }
    
    
    
//    MyNSLog("%@",self.groupUserModel);
    
    [self showActionView];
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
    
    [dict setObject:kPlatform forKey:@"platform"];
    [dict setObject:kVersion forKey:@"version"];
    NSDictionary *postDic = @{
                              @"gid":self.groupUserModel.gid,
                               @"subject":self.subject.text,
                              @"message":self.contentTextView.text,
                              @"pic":multString,
                              };
    
    NSString * postString = [postDic JSONString];
    NSString * encryptPostString = [ClassMethodsViewController encrypt:postString];
    [dict setObject:encryptPostString forKey:@"thread"];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,THREAD_NEW] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        MyNSLog("%@",responseObject);
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            alertContent([responseObject objectForKey:@"msg"]);
            
            
        }else{
            [self.delegate publicationTopicViewControllerWirhReloadData];
            [self.navigationController popViewControllerAnimated:YES];
            
            
        }
        [self hiddenActionView];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
        MyNSLog("%@", operation);

    }];

    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark UITextFieldDelegate
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    
    
    
}


-(void)textFieldDidEndEditing:(UITextField *)textField
{
    
    
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
- (IBAction)cameraClick:(id)sender {
    
//    self.cameraBtn.hidden = YES;
//    if (self.cameraBtn.hidden) {

        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"照相机", @"图片库",nil];
        [alert show];
    
//    }
    
    
}
#pragma mark AlertDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==1) {
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIImagePickerController *pickerImage=[[UIImagePickerController alloc] init];
            pickerImage.delegate=self;
            pickerImage.allowsEditing=YES;
            //pickerImage.mediaTypes              默认是静态图片，指定摄像头获取获取数据类型
            pickerImage.sourceType=UIImagePickerControllerSourceTypeCamera;//指定使用相机
            [self presentViewController:pickerImage animated:YES completion:nil];
        }
        else{
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"警告" message:@"没有摄像头或摄像头损坏" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
            [alert show];
        }
        
    }
    else if(buttonIndex==2)
    {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            UIImagePickerController *pickerImage=[[UIImagePickerController alloc] init];
            pickerImage.delegate=self;
            NSArray * array1=[NSArray arrayWithObjects:(NSString *)kUTTypeImage,(NSString*)kUTTypeMovie, nil];
            pickerImage.mediaTypes=array1;
            pickerImage.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
            pickerImage.allowsEditing=YES;
            [self presentViewController:pickerImage animated:YES completion:nil];
        }
        else
        {
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"警告" message:@"照片库不存在或已损坏" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
            [alert show];
        }
    }
}
#pragma mark ImagepickviewcontrollerDelegate 选择图片后的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:( NSString *)kUTTypeImage]) {
        [self postImage:info];
        [picker dismissViewControllerAnimated:YES completion:^{
        }];
    }
    else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
    {
        [picker dismissViewControllerAnimated:YES completion:^{
        }];
    }
}
/**
 *  上传图片
 *
 *  @param dic 图片的信息
 */
- (void)postImage:(NSDictionary *)dic
{



    UIImage *postImage = [dic objectForKey:UIImagePickerControllerEditedImage];
    

    
    
    [self showActionView];
    NSData* imageData = UIImageJPEGRepresentation(postImage, 0.5);
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@thread/uploadpic/",kBaseURL] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"george.jpg" mimeType:@"image/jpeg"];
        
    } error:nil];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSProgress *progress = nil;
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        [self hiddenActionView];
        if (error) {
            MyNSLog("Error: %@", error);
        } else {
            //图片上传成功
            NSString *status=[NSString stringWithFormat:@"%@",[responseObject valueForKey:@"status"]];
            if ([status isEqualToString:@"1"]) {
                [halfImageURL addObject:[[responseObject valueForKey:@"data"] valueForKey:@"pic"]];
                [imageURlArrays addObject:[[responseObject valueForKey:@"data"] valueForKey:@"url"]];
                self.cameraBtn.hidden = YES;
                self.imageListView.hidden = NO;
                [self.imageArr insertObject:postImage atIndex:self.imageArr.count-1];
                
                [self.imageListView setImages:self.imageArr];
             
            }else
            {
                
            }
        }
    }];
    [uploadTask resume];}
/**
 *  删除上传的图片
 *
 *  @param sender 点击的当前的button
 */
- (void)dodelete:(UIButton *)sender
{

    UIActionSheet *actSheet=[[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"查看大图" otherButtonTitles:@"删除", nil];
    [actSheet showInView:[[UIApplication sharedApplication].delegate window]];
    
}
#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            
            NSInteger count = arrimages.count;
            // 1.封装图片数据
            NSMutableArray *photos = [NSMutableArray arrayWithCapacity:count];
            for (int i = 0; i<count; i++) {
                // 替换为中等尺寸图片
                //            NSString *url = arrimages[i];
                MJPhoto *photo = [[MJPhoto alloc] init];
                photo.image = [arrimages objectAtIndex:i]; // 图片路径
                photo.srcImageView = self.imageListView.subviews[i]; // 来源于哪个UIImageView
                [photos addObject:photo];
            }
            
            // 2.显示相册
            MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
            browser.currentPhotoIndex = indeximage; // 弹出相册时显示的第一张图片是？
            browser.photos = photos; // 设置所有的图片
            [browser show];
            
            
        }
            break;
        case 1:
        {
            
            
            [self showActionView];
            
            NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
            
            [dict setObject:kPlatform forKey:@"platform"];
            [dict setObject:kVersion forKey:@"version"];
            
            
            [dict setObject:[halfImageURL objectAtIndex:indeximage] forKey:@"picurl"];
            
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            [manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,THREAD_DELPIC] parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
                MyNSLog("%@",responseObject);
                NSNumber * statusNum = [responseObject objectForKey:@"status"];
                NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
                NSString * statusString = [numberFormatter stringFromNumber:statusNum];
                if ([statusString isEqualToString:@"0"]) {
                    alertContent([responseObject objectForKey:@"msg"]);
                    
                    
                }else{
                    
                    [halfImageURL removeObjectAtIndex:indeximage];
                    [imageURlArrays removeObjectAtIndex:indeximage];
                    
                    [self.imageArr removeObjectAtIndex:indeximage];
                    [self.imageListView setImages:self.imageArr];
                    if (self.imageArr.count==1) {
                        [UIView animateWithDuration:0.3f animations:^{
                            
                            self.cameraBtn.hidden = NO;
                            self.imageListView.hidden = YES;
                        }];
                    }
                    
                }
                [self hiddenActionView];
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [self hiddenActionView];
                
                
                
                
            }];
            
            
            
            
            
        }
            
            
    break;
    
default:
    break;
}
}
#pragma mark -
#pragma mark -- ImageViewsDelegate
-(void)imageViewsIndex:(NSInteger)index subImageIndex:(NSInteger)imageIndex{
    MyNSLog("%ld",(long)index);
    
    
    if (imageIndex==self.imageArr.count-1) {
          [self cameraClick:nil];
        
 
    }else{
       
        
        arrimages = [[NSMutableArray alloc]initWithCapacity:10];
        
        for (int i=0; i<self.imageArr.count-1; i++) {
            [arrimages addObject:[self.imageArr objectAtIndex:i]];
        }
        indeximage = imageIndex;

        
//
//        int count = arrimages.count;
//        // 1.封装图片数据
//        NSMutableArray *photos = [NSMutableArray arrayWithCapacity:count];
//        for (int i = 0; i<count; i++) {
//            // 替换为中等尺寸图片
//            //            NSString *url = arrimages[i];
//            MJPhoto *photo = [[MJPhoto alloc] init];
//            photo.image = [arrimages objectAtIndex:i]; // 图片路径
//            photo.srcImageView = self.imageListView.subviews[i]; // 来源于哪个UIImageView
//            [photos addObject:photo];
//        }
//        
//        // 2.显示相册
//        browser = [[MJPhotoBrowser alloc] init];
//        browser.currentPhotoIndex = indeximage; // 弹出相册时显示的第一张图片是？
//        browser.photos = photos; // 设置所有的图片
//        [browser show];

        
        
         [self dodelete:nil];
        
        


       }

    

//        int count = arrimages.count;
//        // 1.封装图片数据
//        NSMutableArray *photos = [NSMutableArray arrayWithCapacity:count];
//        for (int i = 0; i<count; i++) {
//            // 替换为中等尺寸图片
//            NSString *url = arrimages[i];
//            MJPhoto *photo = [[MJPhoto alloc] init];
//            photo.url = [NSURL URLWithString:url]; // 图片路径
//            //        photo.srcImageView = self.view.subviews[i]; // 来源于哪个UIImageView
//            [photos addObject:photo];
//        }
//        
//        // 2.显示相册
//        MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
//        browser.currentPhotoIndex = imageIndex; // 弹出相册时显示的第一张图片是？
//        browser.photos = photos; // 设置所有的图片
//        [browser show];
    
    
    
}
//- (void) registerForKeyboardNotifications { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShow:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
//}
//- (void) keyboardWasShow:(NSNotification *) notification { //取得键盘frame，注意，因为键盘是window的层面弹出来的，所以其frame坐标也是对应window窗口的
//    CGRect endRect = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; CGPoint endOrigin = endRect.origin; MyNSLog("keyboard frame = %@",NSStringFromCGRect(endRect));
//    //把键盘的frame坐标转换到与UITextView一致的父view上来
//    endOrigin = [self.view convertPoint:endOrigin fromView:[UIApplication sharedApplication].keyWindow]; MyNSLog("endOrigin = %@",NSStringFromCGPoint(endOrigin));
//    //调整inputView的位置
//    CGFloat inputView_Y = self.view.frame.size.height - endRect.size.height - self.inputView.frame.size.height; [UIView beginAnimations:nil context:nil];
//    self.inputView.frame = CGRectMake(self.inputView.frame.origin.x, inputView_Y, self.inputView.frame.size.width, self.inputView.frame.size.height); [UIView commitAnimations];
//    
//    self.contentView.frame = CGRectMake(self.contentView.frame.origin.x, self.contentView.frame.origin.y, self.contentView.frame.size.width, 20);
//    
//}
//- (void) keyboardWillBeHidden:(NSNotification *) notification {
//        [UIView beginAnimations:nil context:nil];
////    self.inputView.frame = _inputViewOriginalFrame;
//        [UIView commitAnimations];
//}
//- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
//{
//    [self.subject resignFirstResponder];
//    [self.contentTextView resignFirstResponder];
//
//}
@end
